package com.redis.lesson.service;

import com.redis.lesson.mapper.ProductMapper;
import com.redis.lesson.vo.req.ProductVO;
import com.redis.lesson.web.Product;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author gusheng
 * @Date 2021/1/6 19:33
 * @ClassName 类名称
 * @Description 类描述
 * @Version 3.4
 */
@Service
@Slf4j
public class ProductServiceImpl {

    @Autowired
    private ProductMapper productMapper;

    @Autowired
    private RedisTemplate redisTemplate;


    public static final String REDIS_PRODUCT_KEY = "product::";

    @Transactional
    public String addProduct(ProductVO obj) {
        int count = productMapper.addProcuct(obj);
        if(count==1){
            //插入成功后再拿id去查
            Product product = productMapper.getProductByid(obj.getId());
            Map<String, Object> map = objectToMap(product);
            //获得键值,然后缓存Map
            redisTemplate.opsForHash().putAll(REDIS_PRODUCT_KEY+product.getId(),map);
            return "插入数据库成功";
        }
        return "插入数据库失败";
    }


    public Map<String,Object> objectToMap(Object obj) {
        Map<String,Object> map = new HashMap<String,Object>();
        Class<?> clazz = obj.getClass();
        for (Field field: clazz.getDeclaredFields()) {
              field.setAccessible(true);
              String fieldName = field.getName();
              Object value = null;
              try{
                  value = field.get(obj);
              }catch (Exception e){
                  log.error(e.getMessage());
              }
              map.put(fieldName,value);
        }
        return map;
    }

    public Map<String, Object> getProduct(long id) {
        Map<String, Object> map = redisTemplate.opsForHash().entries(REDIS_PRODUCT_KEY + id);
        if(map.isEmpty()){
            System.out.println("查数据库了");
            //未命中,查数据库，在缓存
            Product p = this.productMapper.getProductByid(id);
            map = objectToMap(p);
            redisTemplate.opsForHash().putAll(REDIS_PRODUCT_KEY+id,map);
        }
        return map;
    }

    public void addPrice(int id, int price) {
        this.productMapper.addPrice(id,price);
        //改变缓存中的价格
        Long increment = redisTemplate.opsForHash().increment(REDIS_PRODUCT_KEY + id, "price", price);
        Object o = redisTemplate.opsForHash().get(REDIS_PRODUCT_KEY + id, "price");
        log.info("现在的价格是={}",o);
    }
}
